import { View, Image } from '@tarojs/components'
import { AtRadio, AtButton  } from 'taro-ui'
import Taro from '@tarojs/taro'
import './index.scss'
import headerBg from "../../assets/images/headbg.jpg"
import questions from '../../data/questions.json'
import { useEffect, useState } from 'react'


export default function () {

  //当前题目序号(从1开始)
  const [current, setCurrent] = useState<number>(1)

  // 当前题目
  const [currentQuestion, setCurrentQuestion] = useState(questions[0])

  const questionOptions = currentQuestion.options.map(option => {
    return {
      label: `${option.key}. ${option.value}`,
      value: option.key
    }
  })


  //当前答案 如果答案为空,就禁用下一题按钮,查看结果按钮
  const [currentAnswer, setCurrentAnswer] = useState<string>('')

  // 回答列表
  const [ answerList ] = useState<string[]>([])

  // 监听current变化,修改当前展示的题目和当前回答
  useEffect(() => {
    setCurrentQuestion(questions[current - 1])
    setCurrentAnswer(answerList [current - 1])
  },[current])

  return (
    <View className='do-question'>
      {/* {JSON.stringify(answerList)} */}
      <View className="bg"></View>
      <Image src={headerBg} className='headerBg' mode='aspectFill'/>
      <View className='at-article__h2 title'>{current}、{ currentQuestion.title}</View>
      <View className="options-wrapper">
        <AtRadio options={questionOptions} value={currentAnswer} onClick={(value) => {
          // 选中选项,设置当前答案,设置回答列表当前新项的值
          setCurrentAnswer(value)
          answerList[current - 1] = value
        }}/>
      </View>

      {/* 下一题按钮 */}
      {
        current < questions.length  && (
          <AtButton
            type='primary'
            circle className='controlBtn'
            onClick={() => setCurrent(current + 1)}
            disabled={!currentAnswer}
          >
            下一题
          </AtButton>
        )
      }

      {/* 查看结果按钮 */}
      {
        current === questions.length  && (
          <AtButton
          type='primary'
          circle className='controlBtn'
          disabled={!currentAnswer}
          onClick={() => {
            // 跳转到结果页
            Taro.redirectTo({
              url: '/pages/result/index'
            })
            // 将答案存储在本地
            Taro.setStorageSync('answerList', answerList)
          }}>
            查看结果
          </AtButton>
        )
      }

      {/* 上一题按钮 */}
      {
        current > 1 && (
          <AtButton  type='primary' circle className='controlBtn prev' onClick={() => setCurrent(current - 1)}>上一题</AtButton>
        )
      }
    </View>
  )
}
